package com.longshine.plc.net;

import com.longshine.plc.data.DataSource;
import com.longshine.util.CommonUtil;
import com.longshine.util.NumberUtil;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;

public class UpperMonitorClient extends Thread {

    private Socket client;
    private DataInputStream is;
    private OutputStream os;
    private DataSource source;
    private String connectTime;
    private String clientIp;
    private int clientPort;
    private long lastRecvTime;
    private ServerService server;
    static int cnt = 0;

    public UpperMonitorClient(Socket client, DataSource source, ServerService server) {
        this.client = client;
        this.source = source;
        this.server = server;
        try {
            this.is = new DataInputStream(client.getInputStream());
            this.os = client.getOutputStream();
            this.clientIp = client.getInetAddress().getHostAddress();
            this.clientPort = client.getPort();
            this.connectTime = CommonUtil.getCurrentTime();
            source.log(this.clientIp + ":" + this.clientPort + "连接上");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void stopConn() {
        try {
            this.server.removerClient(this);
            this.source.log(this.clientIp + ":" + this.clientPort + "断开连接");
            if (this.is != null) {
                this.is.close();
                this.is = null;
            }
            if (this.os != null) {
                this.os.close();
                this.os = null;
            }
            if (this.client != null) {
                this.client.close();
                this.client = null;
            }
        } catch (Exception localException) {
        }
    }

    public void run() {
        while (true) {
            try {
                String str = recv();
                if (str != null) {
                    analysisSendByRecv(str);
                } else {
                    stopConn();
                    break;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                stopConn();
                break;
            }
            CommonUtil.delay(50L);
        }
    }

    public void work() {
        start();
    }

    public String recv() throws Exception {
        byte[] buf = new byte[1000];
        try {
            int lent = this.is.read(buf);
            String ret = NumberUtil.toHexStr(buf, lent);
            ret = ret.toUpperCase();
            if (this.lastRecvTime == 0L) {
                this.lastRecvTime = System.currentTimeMillis();
            } else {
                long curTime = System.currentTimeMillis();
                long s = curTime - this.lastRecvTime;
                if (s > 1000L) {
                    this.source.log(this.clientIp + ":" + this.clientPort + "断开了" + s
                            + "ms后重新发送命令");
                }
                this.lastRecvTime = curTime;
            }
        //    Log.println("recv:" + ret);
            return ret;
        } catch (IOException e) {
            throw e;

        }

    }

    public void send(String str) {
        try {
            this.os.write(NumberUtil.str2ByteArr(str));
          //  Log.println("send:" + str);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void analysisSendByRecv(String recv) {
        int len = NumberUtil.hex2Decimal(recv.substring(8, 12));
        int tLen = len * 2 + 12;
        String s = recv.substring(0, tLen);
        sendByRecv(s);
        if (tLen < recv.length()) {
            String leftStr = recv.substring(tLen);
            analysisSendByRecv(leftStr);
        }
    }
    public final static String HEAD = "0000000000LLXX17";

    public String replaceFlag(String s, String flag) {
        String h = s.substring(0, 12);
        String t = s.substring(14);
        return h + flag + t;
    }

    public void sendByRecv(String recv) {
        //00000000000D0117 32C9000136B5000102007B
        String head = recv.substring(0, HEAD.length());
        String tail = recv.substring(HEAD.length());
        String flag = recv.substring(12, 12 + 2);
        //2013-04-26 13:18:12.378 Type:tcpclient address:192.168.1.3:502  Send :00000000000D011732C9000136B5000102007B
//2013-04-26 13:18:12.478 Type:tcpclient address:192.168.1.3:502  Receive :0000000000050117024001
        if (tail.equals("332C000136B5000102007B") || tail.equals("332C000236B500002007B") || tail.equals("332C000336B500002007B")) {
            send(replaceFlag("000000000005FF1702", flag) + source.getEquipPowerValue().toUpperCase());
        } else if (tail.equals("32C9000136B5000102007B") || tail.equals("32C9000236B5000102007B") || tail.equals("32C9000336B5000102007B")) {
            send(replaceFlag("000000000005FF1702", flag) + source.getBerthStationSwitchValue().toUpperCase());
        } else if (tail.equals("332D000136B5000102007B") || tail.equals("332D000236B5000102007B") || tail.equals("332D000336B5000102007B")) {
            send(replaceFlag("000000000005FF170200", flag) + source.getAirCompressValue().toUpperCase());
        } else {
            String s = "000000000009FF1036B1000102";
            s = replaceFlag(s, flag);
            if (recv.startsWith(s)) {
                String dataValue = recv.substring(recv.length() - 4);
                this.source.setBerthControlState(dataValue);
                send(replaceFlag("000000000006FF1036B10001",flag));
            }
            else{
                System.out.println("未知报文:"+recv);
            }
        }
      
 /*       if (("00000000000DFF17332C000136B5000102007B".equals(recv))
                || ("00000000000DFF17332C000236B5000102007B".equals(recv))) {
            send("000000000005FF1702"
                    + this.source.getEquipPowerValue().toUpperCase());
        } else if (("00000000000DFF1732C9000136B5000102007B".equals(recv))
                || ("00000000000DFF1732C9000236B5000102007B".equals(recv))) {
            send("000000000005FF1702"
                    + this.source.getBerthStationSwitchValue().toUpperCase());
        } else if (("00000000000DFF17332D000136B5000102007B".equals(recv))
                || ("00000000000DFF17332D000236B5000102007B".equals(recv))) {
            send("000000000005FF170200"
                    + this.source.getAirCompressValue().toUpperCase());
        } else if (recv.startsWith("000000000009FF1036B1000102")) {
            String dataValue = recv.substring(recv.length() - 4);
            this.source.setBerthControlState(dataValue);
            send("000000000006FF1036B10001");
        }*/
    }

    private String getRadomStr() {
        if (cnt < 25) {
            cnt += 1;
        } else {
            cnt = 0;
        }
        int start = 55;
        start += cnt;
        String s = CommonUtil.toHexStr(start).toUpperCase();
        System.out.println("----" + start + "---" + s);
        return s;
    }
}